<?php
/**
 * Created by PhpStorm.
 * User: daimin
 * Date: 15/7/22
 * Time: 下午6:31
 */

namespace common\services\common;

use common\entities\myhtsq\MyscrmParttimeBusinessEntity;
use common\models\common\ApplicationInfoMappingModel;
use common\repositories\common\MyscrmOrganizationRemindRepository;
use common\repositories\myhtsq\ContractManageRepository;
use common\repositories\myhtsq\ContractOverviewRepository;
use common\repositories\myhtsq\ErpBusinessUnitRepository;
use common\repositories\myhtsq\ErpUserRepository;
use common\repositories\myhtsq\RoleUserRepository;
use common\services\myhtsq\ErpInterfaceService;
use common\services\outstock\FlowCenterService;
use common\support\DateTimeHelper;
use common\services\BaseService;
use common\entities\common\MyscrmApplicationEntity;
use common\entities\common\MyscrmFunctionupgradeEntity;
use common\entities\common\MyscrmOrganizationToAuthorizeEntity;
use common\entities\common\MyscrmOrganizationToPackageEntity;
use common\entities\common\MyscrmPackageEntity;
use common\entities\common\MyscrmPackageToApplicationEntity;
use common\entities\common\MyscrmContractEntity;
use common\repositories\common\MyscrmAuthorizeRepository;
use common\repositories\common\MyscrmContractRepository;
use common\repositories\common\MyscrmApplicationRepository;
use common\repositories\common\MyscrmFunctionupgradeRepository;
use common\repositories\common\MyscrmOrganizationRepository;
use common\repositories\common\MyscrmPackageRepository;
use common\traits\AnchorTrait;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * 合同处理接口类
 * Class MyscrmContractService
 * @package common\services\common
 */
class MyscrmContractService extends BaseService
{

    use AnchorTrait;

    private $_packageRepository = null;
    private $_organizationRepository = null;
    private $_myscrmApplicationRepository;
    private $_contractRepository;
    private $_myscrmAuthorizeRepository;
    private $_myscrmFunctionupgradeRepository;

    public function __construct(MyscrmPackageRepository $packageRepository,
                                MyscrmOrganizationRepository $organizationRepository,
                                MyscrmApplicationRepository $myscrmApplicationRepository,
                                MyscrmContractRepository $contractRepository,
                                MyscrmAuthorizeRepository $myscrmAuthorizeRepository,
                                MyscrmFunctionupgradeRepository $myscrmFunctionupgradeRepository
    )
    {
        $this->_packageRepository = $packageRepository;
        $this->_organizationRepository = $organizationRepository;
        $this->_myscrmApplicationRepository = $myscrmApplicationRepository;
        $this->_contractRepository = $contractRepository;
        $this->_myscrmAuthorizeRepository = $myscrmAuthorizeRepository;
        $this->_myscrmFunctionupgradeRepository = $myscrmFunctionupgradeRepository;
        parent::__construct();
    }

    public function saveContract($contractModel)
    {
        $authInfo = $contractModel['auth_info'];

        if(empty($authInfo)){
            throw new \Exception('授权信息不能为空');
        }

        //过滤正常授权信息与渠道旗舰版授权信息
        $advancedAuthInfo = [];
        $normalAuthInfo = [];
        foreach ($authInfo as $auth){
            if(isset($auth['IsQdAdvanced']) && $auth['IsQdAdvanced'] == 1){
                $advancedAuthInfo[] = $auth;
            }else{
                $normalAuthInfo[] = $auth;
            }
        }

        //保存合同，开启事务
        $connection = MyscrmContractEntity::getDb();
        $transaction = $connection->beginTransaction();

        try {
            $contractId = '';
            if(!empty($normalAuthInfo)){
                $contractModel['auth_info'] = $normalAuthInfo;
                $contractId = $this->saveContractAuth($contractModel);
            }

            //处理渠道管家旗舰版
            if(!empty($advancedAuthInfo)){
                $contractModel['auth_info'] = $advancedAuthInfo;
                $contractModel['order_code'] = '';

                //替换contractId为子合同的contractId
                $childContract = $this->getContractByParentId($contractId);
                if($childContract){
                    $contractModel['contract_id'] = $childContract->ContractId;
                }else{
                    $contractModel['contract_id'] = '';
                }

                $this->saveContractAuth($contractModel, $contractId);
            }

            $transaction->commit();
            return true;
        } catch (\Exception $ex) {
            $transaction->rollBack();
            Yii::error((string)$ex);
            throw new \Exception($ex->getMessage());
        }
    }



    /**
     * 开通信息中手动增加授权
     * @param $contractInfo
     * @param $parentContractId
     * @author zhoud01
     * @return bool
     * @throws \Exception
     */
    public function saveContractByManual($contractModel)
    {
        $authInfo = $contractModel['auth_info'];
        if(empty($authInfo)){
            throw new \Exception('授权信息不能为空');
        }

        //保存合同，开启事务
        $connection = MyscrmContractEntity::getDb();
        $transaction = $connection->beginTransaction();
        try {
            $contractModel['auth_info'] =  $authInfo;
            $this->saveContractAuthByManual($contractModel);
            $transaction->commit();
            return true;
        } catch (\Exception $ex) {
            $transaction->rollBack();
            Yii::error((string)$ex);
            throw new \Exception($ex->getMessage());
        }
    }


    private function getContractByParentId($parentContractId)
    {
        return $this->_contractRepository->getContractByParentId($parentContractId);
    }

    /**
     * 添加合同，新增授权
     * @param $contractInfo
     * @param $parentContractId
     * @return bool
     * @throws \Exception
     */
    private function saveContractAuth($contractInfo, $parentContractId = '')
    {

        if (empty($contractInfo)) {
            throw new \Exception("合同信息不能为空");
        }

        // 检查必要的值
        if (!array_key_exists('contract_num', $contractInfo) || !array_key_exists('party_a', $contractInfo) ||
            !array_key_exists('contract_type', $contractInfo) || !array_key_exists('begin_on', $contractInfo) ||
            !array_key_exists('end_on', $contractInfo) || !array_key_exists('organization_id', $contractInfo) ||
            !array_key_exists('auth_info', $contractInfo) || !array_key_exists('area_id', $contractInfo) || !array_key_exists('establish_time', $contractInfo)
        ) {
            throw new \Exception("缺少参数");
        }

        //验证auth_info必须是数组
        if (!is_array(ArrayHelper::getValue($contractInfo, 'auth_info'))) {
            throw new \Exception("auth_info必须是数组");
        }

        // 查询指定的organization_id是否存在
        $organizationId = ArrayHelper::getValue($contractInfo, 'organization_id');
        $orgObj = $this->_organizationRepository->getById($organizationId);
        if (empty($orgObj)) {
            throw new \Exception("不存在的租户信息");
        }

        //$contractNum = ArrayHelper::getValue($contractInfo, 'contract_num');
        //$contractObj = $this->_contractRepository->getContractByContractNum($contractNum, $organizationId);
        // 新增检查合同号是否存在, 存在就是提示错误
        //if (empty($contractInfo['contract_id']) && !empty($contractObj)) {
        //    throw new \Exception("合同号已存在不允许覆盖");
        //}

        //如果该流程单号已经关联了某授权则不允许使用该流程单号
        if (empty($contractInfo['contract_id']) && !empty($contractInfo["order_code"])) {
            $exists = $this->_contractRepository->checkExistsByOrderCode($contractInfo["order_code"]);
            if ($exists) {
                throw new \Exception("该出库单号已经关联过授权");
            }
        }

        // 检查购买类型，如果已经商户已存在授权就是增购或者续签，否则就是新增
        $orgContractCount = intval($this->_contractRepository->getContractByOrganizationId($organizationId));
        $contractType = intval(ArrayHelper::getValue($contractInfo, 'contract_type'));
        if(empty($parentContractId)) {//只有父级需要判断
            if ($orgContractCount > 0) {
                //已存在该商户的合同，那么之后的新增的合同都是增购的了
                if ($contractType == 1 && empty($contractInfo['contract_id'])) {
                    throw new \Exception("购买类型不对，应该为增购或续签");
                }
            } else {
                if ($contractType == 2 || $contractType == 3) {
                    throw new \Exception("购买类型不对，应该为新增");
                }
            }
        }

        // 验证日期格式
        if (!DateTimeHelper::validateDate(ArrayHelper::getValue($contractInfo, 'begin_on')) || !DateTimeHelper::validateDate(ArrayHelper::getValue($contractInfo, 'end_on'))) {
            throw new \Exception("租期，时间格式不对");
        }

        // 租期，结束时间不能小于开始时间
        if (strtotime(ArrayHelper::getValue($contractInfo, 'begin_on')) > strtotime(ArrayHelper::getValue($contractInfo, 'end_on'))) {
            throw new \Exception("租期，结束时间不能小于开始时间");
        }

        // 授权授不能小于已用授权数(需要从auth_info中获取)
        $authInfo = ArrayHelper::getValue($contractInfo, 'auth_info');
        if (!empty($authInfo) && is_array($authInfo)) {
            foreach ($authInfo as $aInfo) {
                if (intval(ArrayHelper::getValue($aInfo, 'total_num')) < intval(ArrayHelper::getValue($aInfo, 'used_num'))) {
                    throw new \Exception("授权数不能小于已用授权数");
                }
            }
        }

        //如果是新增则 交付信息默认取租户中的
        if (empty($contractInfo['contract_id'])) {
            $contractInfo['CustomManager'] = isset($orgObj->CustomManager) ? $orgObj->CustomManager : "";
            $contractInfo['CustomManagerPhone'] = isset($orgObj->CustomManagerPhone) ? $orgObj->CustomManagerPhone : "";
            $contractInfo['CustomManagerEmail'] = isset($orgObj->CustomManagerEmail) ? $orgObj->CustomManagerEmail : "";
            $contractInfo['Deliver'] = isset($orgObj->Deliver) ? $orgObj->Deliver : "";
            $contractInfo['DeliverPhone'] = isset($orgObj->DeliverPhone) ? $orgObj->DeliverPhone : "";
            $contractInfo['DeliverEmail'] = isset($orgObj->DeliverEmail) ? $orgObj->DeliverEmail : "";
        }

        try {
            $contractId = $this->_contractRepository->saveContract($contractInfo, $parentContractId);

            foreach ($authInfo as $aInfo) {
                $this->_myscrmAuthorizeRepository->saveOrganizationToAuthorize($organizationId, $contractId, $aInfo);
            }

            //只有在选择了流程单号以及新建的时才触发
            if (!empty($contractInfo["order_code"]) && empty($contractInfo["contract_id"])) {
                /* @var $flowCenterService FlowCenterService */
                $flowCenterService = \Yii::createObject(FlowCenterService::className());
                $ret = $flowCenterService->addAuthContract($contractInfo["order_code"], $contractInfo["contract_num"]);
                if (false === $ret) {
                    throw new \Exception($flowCenterService->getErrMsg());
                }
            }

            return $contractId;
        } catch (\Exception $ex) {
            Yii::error((string) $ex);
            throw new \Exception($ex->getMessage());
        }

    }

    /**
     * 添加合同，新增授权
     * @param $contractInfo
     * @author zhoud01
     * @since 2017-7-23
     * @param $parentContractId
     * @return bool
     * @throws \Exception
     */
    private function saveContractAuthByManual($contractInfo, $parentContractId = '')
    {

        if (empty($contractInfo)) {
            throw new \Exception("合同信息不能为空");
        }

        // 检查必要的值
        if (!array_key_exists('contract_num', $contractInfo) || !array_key_exists('party_a', $contractInfo) ||
            !array_key_exists('contract_type', $contractInfo) || !array_key_exists('begin_on', $contractInfo) ||
            !array_key_exists('end_on', $contractInfo) || !array_key_exists('organization_id', $contractInfo) ||
            !array_key_exists('auth_info', $contractInfo) || !array_key_exists('area_id', $contractInfo) || !array_key_exists('establish_time', $contractInfo)
        ) {
            throw new \Exception("缺少参数");
        }

        //验证auth_info必须是数组
        if (!is_array(ArrayHelper::getValue($contractInfo, 'auth_info'))) {
            throw new \Exception("auth_info必须是数组");
        }

        // 查询指定的organization_id是否存在
        $organizationId = ArrayHelper::getValue($contractInfo, 'organization_id');
        $orgObj = $this->_organizationRepository->getById($organizationId);
        if (empty($orgObj)) {
            throw new \Exception("不存在的租户信息");
        }

        //$contractNum = ArrayHelper::getValue($contractInfo, 'contract_num');
        //$contractObj = $this->_contractRepository->getContractByContractNum($contractNum, $organizationId);
        // 新增检查合同号是否存在, 存在就是提示错误
        //if (empty($contractInfo['contract_id']) && !empty($contractObj)) {
        //    throw new \Exception("合同号已存在不允许覆盖");
        //}

        //如果该流程单号已经关联了某授权则不允许使用该流程单号
        if (empty($contractInfo['contract_id']) && !empty($contractInfo["order_code"])) {
            $exists = $this->_contractRepository->checkExistsByOrderCode($contractInfo["order_code"]);
            if ($exists) {
                throw new \Exception("该出库单号已经关联过授权");
            }
        }

        // 检查购买类型，如果已经商户已存在授权就是增购或者续签，否则就是新增
        $orgContractCount = intval($this->_contractRepository->getContractByOrganizationId($organizationId));
        $contractType = intval(ArrayHelper::getValue($contractInfo, 'contract_type'));
        if(empty($parentContractId)) {//只有父级需要判断
            if ($orgContractCount > 0) {
                //已存在该商户的合同，那么之后的新增的合同都是增购的了
                if ($contractType == 1 && empty($contractInfo['contract_id'])) {
                    throw new \Exception("购买类型不对，应该为增购或续签");
                }
            } else {
                if ($contractType == 2 || $contractType == 3) {
                    throw new \Exception("购买类型不对，应该为新增");
                }
            }
        }

        // 验证日期格式
        if (!DateTimeHelper::validateDate(ArrayHelper::getValue($contractInfo, 'begin_on')) || !DateTimeHelper::validateDate(ArrayHelper::getValue($contractInfo, 'end_on'))) {
            throw new \Exception("租期，时间格式不对");
        }

        // 租期，结束时间不能小于开始时间
        if (strtotime(ArrayHelper::getValue($contractInfo, 'begin_on')) > strtotime(ArrayHelper::getValue($contractInfo, 'end_on'))) {
            throw new \Exception("租期，结束时间不能小于开始时间");
        }

        // 授权授不能小于已用授权数(需要从auth_info中获取)
        $authInfo = ArrayHelper::getValue($contractInfo, 'auth_info');
        if (!empty($authInfo) && is_array($authInfo)) {
            foreach ($authInfo as $aInfo) {
                if (intval(ArrayHelper::getValue($aInfo, 'total_num')) < intval(ArrayHelper::getValue($aInfo, 'used_num'))) {
                    throw new \Exception("授权数不能小于已用授权数");
                }
            }
        }

        //如果是新增则 交付信息默认取租户中的
        if (empty($contractInfo['contract_id'])) {
            $contractInfo['CustomManager'] = isset($orgObj->CustomManager) ? $orgObj->CustomManager : "";
            $contractInfo['CustomManagerPhone'] = isset($orgObj->CustomManagerPhone) ? $orgObj->CustomManagerPhone : "";
            $contractInfo['CustomManagerEmail'] = isset($orgObj->CustomManagerEmail) ? $orgObj->CustomManagerEmail : "";
            $contractInfo['Deliver'] = isset($orgObj->Deliver) ? $orgObj->Deliver : "";
            $contractInfo['DeliverPhone'] = isset($orgObj->DeliverPhone) ? $orgObj->DeliverPhone : "";
            $contractInfo['DeliverEmail'] = isset($orgObj->DeliverEmail) ? $orgObj->DeliverEmail : "";
        }

        try {
            $contractId = $this->_contractRepository->saveContract($contractInfo, $parentContractId);

            foreach ($authInfo as $aInfo) {
                $this->_myscrmAuthorizeRepository->saveOrganizationToAuthorize($organizationId, $contractId, $aInfo);
            }

            //只有在选择了流程单号以及新建的时才触发
            if (!empty($contractInfo["order_code"]) && empty($contractInfo["contract_id"])) {
                /* @var $flowCenterService FlowCenterService */
                $flowCenterService = \Yii::createObject(FlowCenterService::className());
                $ret = $flowCenterService->addAuthContract($contractInfo["order_code"], $contractInfo["contract_num"]);
                if (false === $ret) {
                    throw new \Exception($flowCenterService->getErrMsg());
                }
            }

            return $contractId;
        } catch (\Exception $ex) {
            Yii::error((string) $ex);
            throw new \Exception($ex->getMessage());
        }

    }



    /**
     * 通过租户ID，拿到其合同列表
     * @param $orgId
     * @return array
     * @throws \Exception
     */
    public function getContractsByOrgId($orgId)
    {

        if (empty($orgId)) {
            throw new \Exception("租户ID不能为空");
        }
        $contracts = $this->_contractRepository->getContractByOrganizationId($orgId);
        return $contracts;
    }

    /**
     * 根据合同号获取合同详情
     * @param $contractId
     * @return MyscrmContractEntity
     * @throws \Exception
     */
    public function getContractById($contractId)
    {
        if (empty($contractId)) {
            throw new \Exception("合同ID不能为空");
        }

        return $contract = $this->_contractRepository->getContractById($contractId);
    }

    /**
     * 作废合同
     */
    public function cancelContract($orgName, $contractId)
    {
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }

        if (empty($contractId)) {
            throw new \Exception("租户合同ID不能为空");
        }

        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if (empty($orgId)) {
            throw new \Exception("租户不存在");
        }

        $contractObj = $this->_contractRepository->getContractById($contractId);
        if (empty($contractObj)) {
            throw new \Exception("租户合同不存在");
        }

        $this->_contractRepository->updateStatus($orgId, $contractId, 2);  //作废
    }

    /**
     * 根据租户名称拿到合同列表，包括授权信息
     * @param $orgName
     * @return array
     * @see formatContractList
     */
    public function getContractsList($orgName)
    {
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        $contractList = $this->_contractRepository->getContractByOrganizationId($orgId);
        $applicationList = $this->_myscrmApplicationRepository->getAll(false);
        $authList = $this->_myscrmAuthorizeRepository->getAuthorizeListByOrgId($orgId);
        $authUsedList = $this->_myscrmAuthorizeRepository->getUsedAuthorizeNum($orgName);
        return $this->formatContractList($contractList, $applicationList, $authList, $authUsedList);

    }

    /**
     * 通过租户企业号和合同ID获取合同详情
     * @param $orgName 租户名称
     * @param $contractId
     * @return array
     * @throws \Exception
     */
    public function getContractDetailById($orgName, $contractId)
    {
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }

        $orgId = $this->_organizationRepository->getOrgId($orgName);

        if (empty($orgId)) {
            throw new \Exception("不存在的租户");
        }

        if (empty($contractId)) {
            throw new \Exception("合同ID不能为空");
        }

        return $this->_contractRepository->getContractDetailById($orgId, $contractId);
    }

    /**
     * @param $contractList \common\entities\common\MyscrmContractEntity[]
     * @param $applicationList \common\entities\common\MyscrmApplicationEntity[]
     * @param $authList \common\entities\common\MyscrmOrganizationToAuthorizeEntity[]
     * @param $authUsedList array [[AuthorizeId=>count],...]
     * @return array ['nums' =>['total_num' => $totalCount, 'used_num' => $totalUsedCunt],
     * 'contracts' => $contracts]
     */
    private function formatContractList($contractList, $applicationList, $authList, $authUsedList)
    {
        $totalCount = 0;
        $totalUsedCount = 0;

        //格式化每个应用的数据,并按合同Id分组
        /** @var \common\entities\common\MyscrmApplicationEntity[] $applicationIndexById */
        $applicationIndexById = ArrayHelper::index($applicationList, 'ApplicationId');

        /** @var ApplicationInfoMappingModel $mapping */
        $mapping = Yii::createObject(ApplicationInfoMappingModel::className());
        $applicationList = $mapping->getAvailableBusinessApplicationList();

        $authIndexByContractId = [];
        foreach ($authList as $auth) {
            if (!array_key_exists($auth->ApplicationId, $applicationIndexById)) {
                continue;
            }
            $authUsedCount = isset($authUsedList[$auth->Id]) ? $authUsedList[$auth->Id] : 0;
            $authArray = [
                'id' => $auth->ApplicationId,
                'friendly_name' => $applicationIndexById[$auth->ApplicationId]->FriendlyName,
                'unique_name' => $applicationIndexById[$auth->ApplicationId]->UniqueName,
                'order_by' => $applicationIndexById[$auth->ApplicationId]->OrderBy,
                'total_num' => $auth->TotalNum,
                'used_num' => $authUsedCount,
            ];

            if($auth->IsQdAdvanced){
                $authArray['friendly_name'] = '渠道管家(旗舰版)';
                $authArray['IsQdAdvanced'] = '1';
            }

            //填充合同产品中的主数据
            if($auth->application_info_id && isset($applicationList[$auth->application_info_id])){
                $authArray['application_info_id'] = $auth->application_info_id;
                $authArray['friendly_name'] = $applicationList[$auth->application_info_id]['apply_name'];
            }

            $authIndexByContractId[$auth->ContractId][] = $authArray;

            $totalCount += $auth->TotalNum;
            $totalUsedCount += $authUsedCount;
        }

        //处理渠道管家旗舰版授权信息
        foreach ($contractList as $contract) {
            if($contract->ParentContractId){
                $authInfo = $authIndexByContractId[$contract->ContractId];
                if(!empty($authInfo)){
                    $parentAuthInfo = $authIndexByContractId[$contract->ParentContractId];

                    $tmp = array_merge($parentAuthInfo, $authInfo);
                    $authIndexByContractId[$contract->ParentContractId] = $tmp;
                }
            }
        }

        $contracts = [];
        foreach ($contractList as $contract) {

            //子级授权不展示
            if($contract->ParentContractId){
                continue;
            }

            if ($contract->Status == 1 && MyscrmContractEntity::isContractOverdue($contract)) {
                $contract->Status = 3;
            }
            $contractArray = $contract->toArray();
            $contractArray['packages'] = isset($authIndexByContractId[$contract->ContractId]) ? $authIndexByContractId[$contract->ContractId] : [];
            usort($contractArray['packages'], function ($a, $b) {
                return $a['order_by'] - $b['order_by'];
            });
            //根据 兑现责任人ID promiseFulfilPrinciple 或者名字
            $contractArray['promiseFulfilPrincipleName'] = "";
            if (!empty($contractArray["promiseFulfilPrinciple"])) {
                $userInfo = ErpUserRepository::getUserInfoById($contractArray["promiseFulfilPrinciple"]);
                $contractArray['promiseFulfilPrincipleName'] = isset($userInfo["UserName"]) ? $userInfo["UserName"] : "";
            }
            $contracts[] = $contractArray;
        }

        return ['nums' => ['total_num' => $totalCount, 'used_num' => $totalUsedCount],
            'contracts' => $contracts];
    }

    public function getAllListByContractId($ContractNums)
    {
        return $this->_contractRepository->getAllListByContractId($ContractNums);
    }

    private function __orgProjectAuthListFindData($areaId, $disable, $orgState, $keyword)
    {
        $chooseAll = false;
        if ($areaId == "") {
            $chooseAll = true;
        }
        #权限过滤
        //三类用户：
        //普通用户，只能看到和自己相关的数据，自己是交付顾问或客户经理；
        //区域负责人，可以看到本区域的所有数据，可以更新交付信息；
        //领导层（姚大、剑峰等）可以查看所有区域的数据。
        $userEntity = ErpInterfaceService::getUserByCode(\Yii::$app->user->identity->usercode);
        $isAreaOwner = $this->__checkIsAreaOwner($userEntity);

        #配置文件里的用户显示全部区域数据
        if (!in_array($userEntity->UserGUID, \Yii::$app->params['allAuthUserId'])
            && $userEntity->BUGUID != '11b11db4-e907-4f1f-8835-b9daab6e1f23' &&
            $userEntity->BUGUID != '6e2a7816-8e27-4b19-9428-628259bd8eda'
        ) {
            $buGUIDList = [];
            $parttimeBUGUIDs = MyscrmParttimeBusinessEntity::find()->where(['user_guid' => $userEntity->UserGUID])->all();
            foreach ($parttimeBUGUIDs as $k => $v) {
                $buGUIDList = array_merge($buGUIDList, ErpInterfaceService::getSubBuGuidsByBuGuid($v->bu_guid));
            }

            $areaIds = array_merge($buGUIDList, ErpInterfaceService::getSubBuGuidsByBuGuid($userEntity->BUGUID));

            //非配置文件里的用户查看全部数据时，只能查看自己区域的数据
            if ($areaId == '') {
                $areaId = $areaIds;
            }

        }

        //查找数据
        $data = $this->_organizationRepository->getOrgProjectAuthList($userEntity, $isAreaOwner, $areaId, $disable, $orgState, $keyword, $chooseAll);
        return $data;
    }

    /**
     * 检查是否区域负责人
     * @param $userEntity
     * @return bool
     * @throws \yii\base\InvalidConfigException
     */
    private function __checkIsAreaOwner($userEntity)
    {
        /** @var RoleUserRepository $roleUserRepository */
        $roleUserRepository = \Yii::createObject(RoleUserRepository::className());
        $roleInfo = $roleUserRepository->getRoleIdsByUserId($userEntity->UserGUID);
        if (in_array(15, $roleInfo)) {
            return true;
        }

        return false;
    }

    /**
     * 更新交付信息
     * @param $info
     * @return bool
     * @throws \Exception
     */
    public function updateContractDeliverInfo($info)
    {
        if (!array_key_exists('contract_id', $info)) {
            throw new \Exception("合同不能为空");
        }

        return $this->_contractRepository->updateContractDeliverInfo($info);
    }

    /**
     * 获取交付信息变更记录
     * @param $contractId
     * @return mixed
     */
    public function getContractDeliveryChangeLog($contractId)
    {
        return $this->_contractRepository->getContractDeliveryChangeLog($contractId);
    }

    /**
     * 租户、合同、项目数量概览
     * @return array
     * @throws \yii\base\InvalidConfigException
     */
    public function getContractOverview()
    {
        /* @var $myscrmOrganizationService MyscrmOrganizationService */
        $myscrmOrganizationService=\Yii::createObject(MyscrmOrganizationService::className());
        $data=$myscrmOrganizationService->getAllAuthProject('', '', '', '');
        //装拼返回数据
        $organizationIds = ArrayHelper::getColumn($data, 'OrganizationId');
        $organizationIds = array_unique($organizationIds);

        $contractIds = ArrayHelper::getColumn($data, 'contractId');

        $projectIds = ArrayHelper::getColumn($data, 'ProjId');
        $projectIds = array_unique($projectIds);

        //返回结果
        $result = [];
        $result["orgCount"] = count($organizationIds);
        $result["contractCount"] = count($contractIds);
        $result["projectCount"] = count($projectIds);

        return $result;
    }

    public function getContractByContractNum($contractNum, $organizationId = null)
    {
        return $this->_contractRepository->getContractByContractNum($contractNum, $organizationId);
    }
}
